package com.cium.aqie.coroutine.basic

import com.cium.aqie.coroutine.common.HttpException
import com.cium.aqie.coroutine.common.HttpService
import com.cium.aqie.coroutine.common.log
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.startCoroutine
import kotlin.coroutines.suspendCoroutine

/**
 * @Function:
 * @Author: aqie
 * @Date: 2019/9/2 19:47
 */
fun 我要开始协程啦(block: suspend ()-> Unit){
    block.startCoroutine(BaseContinuation())
}

suspend fun 我要开始加载图片啦(url: String) = suspendCoroutine<ByteArray> {
    continuation ->
    log("耗时操作，下载图片")
    try {
        val responseBody = HttpService.service.getLogo(url).execute()
        if(responseBody.isSuccessful){
            responseBody.body()?.byteStream()?.readBytes()?.let(continuation::resume)
        }else{
            continuation.resumeWithException(HttpException(responseBody.code()))
        }
    } catch(e: Exception) {
        continuation.resumeWithException(e)
    }
}